<template>
	<view>
		<!-- 海报 -->
		<cover-image class="del" @click="closeCans" :src="static('del','.png')"></cover-image>
		<canvas :disable-scroll="false" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"  canvas-id="zwyPoster" :style="{width:cansWidth,height:cansHeight}" class="isCan"></canvas>
		<view class="bg" @click="closeCans"></view>
		<view class="fixedBox" @click="saveCans">
			保存图片
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			poster: Object
		},
		data() {
			return {
				// 海报
				// cansWidth: 270, //海报宽度
				// cansHeight: 480 //海报高度
				// 海报
				shareBgs: []
			};
		},
		beforeMount() {
			this.poster.desc = this.formatDesc(this.poster.desc);
			this.shareBgs = uni.getStorageSync('shareBgs')
		},
		mounted() {
			this.ctx = uni.createCanvasContext('zwyPoster', this);
			uni.showLoading({
				title: '生成海报ing...',
				mask: true
			})
			
			//绘制海报底色为白色
			this.drawBaseBg('white');
			/**
			 * 绘制圆角矩形
			 * @param {Object} ctx - canvas组件的绘图上下文
			 * @param {Number} x - 矩形的x坐标
			 * @param {Number} y - 矩形的y坐标
			 * @param {Number} w - 矩形的宽度
			 * @param {Number} h - 矩形的高度
			 * @param {Number} r - 矩形的圆角半径
			 * @param {String} [c = 'transparent'] - 矩形的填充色
			 */
			// 绘制海报 背景
			this.roundRect(
				this.ctx,
				0,
				0,
				this.cansWidth,
				this.cansHeight,
				uni.upx2px(20), '#F0F0F0')
			this.ctx.clip();
			/*
				绘制图片
				调用方式:this.drawBg({
					url:'',路径
					sLeft:0~1 | 'center' 百分比离左边距离 1则为100vw,
					sTop:0~1 百分比离顶部距离,
					sWidth:0~1 百分比宽度，
					sHeight:0~1 百分比高度
				})
			*/
			this.drawBg({
				url: this.shareBgs[0],
				sLeft: 0,
				sTop: 0,
				sWidth: .4173,
				sHeight: 0.3
			})
			this.drawBg({
				url: this.shareBgs[1],
				sLeft: .5827,
				sTop: 0.7424,
				sWidth: .4173,
				sHeight: 0.3
			})
			// 绘制海报 小背景
			this.roundRect(
				this.ctx,
				this.cansWidth * 0.0426, this.cansHeight * 0.024, this.cansWidth * 0.91467, this.cansHeight * 0.952,
				uni.upx2px(20), 'rgba(255, 255, 255, 0.7)');

			this.drawBg({
				url: this.shareBgs[2],
				sLeft: 'center',
				sTop: 0.7424,
				sWidth: 0.2406,
				sHeight: .1354
			})

			/*
				绘制头像
				绘制头像需要添加域名白名单	downloadFile合法域名	https://wx.qlogo.cn
				调用方式:this.circleImg(img, x, y, r) 
				img:图片路径
				x:0~1 百分比离左边距离,
				y:0~1 百分比离顶部距离
			*/
			this.circleImg(
				this.poster.src, .1975,
				.22)
			/*
				绘制单行文本
				调用方式:this.drawText({
					text:'文本', String || Array
					sLeft:0~1 || 'center' 百分比离左边距离,
					sTop:0~1 百分比离顶部距离,
					fontSize:Number 文字大小,
					color:'' 颜色,
					bold:Boolean 粗体,
					lineHeight:Number //如果是数组则设置行高
				})
			*/
			if (this.poster.author) {
				this.drawText({
					text: `灵魂画师`,
					sLeft: .158,
					sTop: 0.101,
					fontSize: 12,
					color: '#1A1B1E'
				})
				this.drawText({
					text: this.poster.author,
					sLeft: .35,
					sTop: 0.101,
					fontSize: 13,
					color: '#457EEC'
				})
				this.drawText({
					text: `的作品`,
					sLeft: .6,
					sTop: 0.101,
					fontSize: 12,
					color: '#1A1B1E'
				})
				this.drawText({
					text: '快来围观~',
					sLeft: .158,
					sTop: 0.144,
					fontSize: 12,
					color: '#2C2D30'
				})
			} else {
				this.drawText({
					text: '脑洞大开，接下来到你了',
					sLeft: .158,
					sTop: 0.101,
					fontSize: 12,
					color: '#0D0E11'
				})
				this.drawText({
					text: '“' + this.poster.huati + '”',
					sLeft: .13,
					sTop: 0.144,
					fontSize: 12,
					color: '#2C2D30'
				})
			}

			// 绘制多行文本
			this.drawPara({
				para: this.poster.desc, //文本
				fontSize: 10, //字体大小
				sLeft: .12, //百分比离左边距离
				sTop: .63, //百分比李作边距离
				titleHeight: 16, //一行高度
				sMaxWidth: .7, //一行最大宽度
				redWord: [], //关键字
				color: '#777777', //正常颜色
				redColor: '#DD524D', //高亮颜色
				bold: false //是否加粗
			})
			// 绘制装饰线
			this.drawLine([{
					x: 118,
					y: 790
				},
				{
					x: 95,
					y: 790
				},
				{
					x: 95,
					y: 813
				}
			])
			this.drawLine([{
					x: 630,
					y: 933
				},
				{
					x: 653,
					y: 933
				},
				{
					x: 653,
					y: 910
				}
			])
			uni.hideLoading()
		},
		computed: {
			today() {
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1
				let date = new Date().getDate()
				let time = year + "年" + month + "月" + date + "日"
				return time
			},
			cansWidth() {
				return uni.upx2px(557)
			},
			cansHeight() {
				return uni.upx2px(990)
			},
		},
		methods: {
			formatDesc(desc) {
				if (desc.length < 57) {
					return desc;
				}

				let target = [],
					start = 0,
					end = 19,
					i = 1;
				while (i <= 3) {
					if (end > desc.length) {
						end = desc.length;
					}
					target.push(desc.slice(start, end))
					start += 19;
					end += 19;
					i++;
				}
				console.log(target[0], '===', target[1], '===', target[2])
				return target[0] + target[1] + target[2].slice(0, 15) + '...'
			},
			drawLine(dots, color = '#D8D8D8') {
				this.ctx.strokeStyle = color;
				this.ctx.lineWidth = 3;
				// this.ctx.lineJoin = 'bevel';
				// this.ctx.lineCap = 'round';
				this.ctx.beginPath();
				let moveDot = {
					x: (dots[0].x * this.cansWidth) / 750,
					y: (dots[0].y * this.cansHeight) / 1334
				}
				this.ctx.moveTo(moveDot.x, moveDot.y);
				dots.forEach((dot, i) => {
					// || i == dots.length - 1
					if (i == 0) {

					} else {
						this.ctx.lineTo((dot.x * this.cansWidth) / 750, (dot.y * this.cansHeight) / 1334)
					}
				});
				this.ctx.stroke();
				this.ctx.closePath();
			},
			drawBaseBg(bgColor) {
				this.ctx.rect(0, 0, this.cansWidth, this.cansHeight)
				this.ctx.setFillStyle(bgColor)
				this.ctx.fill()
				this.ctx.draw(true)
			},
			/**
			 * 绘制圆角矩形
			 * @param {Object} ctx - canvas组件的绘图上下文
			 * @param {Number} x - 矩形的x坐标
			 * @param {Number} y - 矩形的y坐标
			 * @param {Number} w - 矩形的宽度
			 * @param {Number} h - 矩形的高度
			 * @param {Number} r - 矩形的圆角半径
			 * @param {String} [c = 'transparent'] - 矩形的填充色
			 */
			roundRect(ctx, x, y, w, h, r, c = '#fff') {
				if (w < 2 * r) {
					r = w / 2;
				}
				if (h < 2 * r) {
					r = h / 2;
				}

				ctx.beginPath();
				ctx.fillStyle = c;

				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
				ctx.moveTo(x + r, y);
				ctx.lineTo(x + w - r, y);
				ctx.lineTo(x + w, y + r);

				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
				ctx.lineTo(x + w, y + h - r);
				ctx.lineTo(x + w - r, y + h);

				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
				ctx.lineTo(x + r, y + h);
				ctx.lineTo(x, y + h - r);

				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
				ctx.lineTo(x, y + r);
				ctx.lineTo(x + r, y);

				ctx.fill();
				ctx.closePath();
			},
			circleImg(img, x, y) {
				uni.getImageInfo({
					src: img
				}).then((image) => {
					x = Math.ceil(this.cansWidth * x)
					y = Math.ceil(this.cansHeight * y)
					this.ctx.save();
					this.roundRect(this.ctx, x, y, uni.upx2px(347), uni.upx2px(347), uni.upx2px(12));
					this.ctx.clip();
					this.ctx.drawImage(image[1].path, x, y, uni.upx2px(347), uni.upx2px(347));
					this.ctx.restore();
					this.ctx.draw(true);
				})
			},
			closeCans() {
				this.$parent.posterShow = false;
				this.$parent.$parent.isScroll = true;
			},
			saveCans() {
				let that = this;
				uni.showLoading({
					title: '保存ing...',
					mask: true
				})
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: this.cansWidth * 1.5,
					height: this.cansHeight * 1.5,
					destWidth: this.cansWidth * 3,
					destHeight: this.cansHeight * 3,
					canvasId: 'zwyPoster',
					success: function(res) {
						uni.hideLoading()
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(res) {
								uni.showToast({
									title: '保存相册成功'
								})
							},
							fail(res) {
								if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
									uni.showModal({
										title: '您需要授权相册权限',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {

													},
													fail(res) {

													}
												})
											}
										}
									})
								}
							}
						});
					},
					fail(res) {
						uni.hideLoading()
					},
					complete() {
						that.closeCans()
					}
				}, this)
			},
			drawPara(item) {
				var redIndexObj = {}
				if (item.redWord.length > 0) {
					for (var i = 0; i < item.redWord.length; i++) {
						let startIndex = 0,
							index;
						while ((index = item.para.indexOf(item.redWord[i], startIndex)) > -1) {
							redIndexObj[index] = true;
							for (var j = 0; j < item.redWord[i].length; j++) {
								redIndexObj[index + j] = true
							}
							startIndex = index + 1;
						}
					}
				}
				this.ctx.font = `normal normal ${item.fontSize}px sans-serif`;
				this.ctx.setFillStyle(item.color)
				var isLeft
				if (item.sLeft == 'center') {
					isLeft = this.cansWidth * (.5 - item.sMaxWidth / 2) - item.fontSize
				} else {
					isLeft = item.sLeft * this.cansWidth
				}
				var maxWidth = Math.floor(this.cansWidth * item.sMaxWidth)
				var tempList = item.para.split('')
				var nowText = '',
					isCol = 0,
					textWidth = 0
				for (var i = 0; i < tempList.length; i++) {
					if (i > 0) {
						nowText += tempList[i - 1]
					} else {
						nowText += tempList[0]
					}
					textWidth = this.ctx.measureText(nowText).width
					if (textWidth > maxWidth) {
						isCol++
						nowText = '占'
						textWidth = this.ctx.measureText(nowText).width
					}
					if (redIndexObj[i]) {
						this.ctx.save()
						if (item.bold) this.ctx.font = `normal bold ${item.fontSize}px sans-serif`;
						this.ctx.setFillStyle(item.redColor)
					}
					this.ctx.fillText(tempList[i], isLeft + textWidth, item.sTop * this.cansHeight + item.titleHeight * isCol)
					this.ctx.restore()
				}
				this.ctx.draw(true)
			},
			drawBg(item) {
				let that = this;
				if (item.sLeft == 'center') {
					that.ctx.drawImage(item.url, that.cansWidth * (.5 - item.sWidth / 2), that.cansHeight * item.sTop, that.cansWidth *
						item.sWidth, that.cansHeight * item.sHeight);
					
				} else {
					that.ctx.drawImage(item.url, that.cansWidth * item.sLeft, that.cansHeight * item.sTop, that.cansWidth * item
						.sWidth,
						that.cansHeight * item.sHeight);


				}
				that.ctx.draw(true);
			},
			drawText(item) {
				var isLeft
				if (item.sLeft == 'center') {
					isLeft = this.cansWidth * .5 - (item.fontSize * item.text.length) / 2
				} else {
					isLeft = item.sLeft * this.cansWidth
				}
				this.ctx.save()
				if (item.bold) this.ctx.font = `normal bold ${item.fontSize}px sans-serif`;
				this.ctx.setFillStyle(item.color)
				this.ctx.setFontSize(item.fontSize)
				if (item.text instanceof Array) {
					if (!item.lineHeight) item.lineHeight = item.fontSize + 2

					for (var i = 0; i < item.text.length; i++) {
						this.ctx.fillText(item.text[i], isLeft, item.sTop * this.cansHeight + item.lineHeight * i)
					}
				} else {
					this.ctx.fillText(item.text, isLeft, item.sTop * this.cansHeight)
				}
				this.ctx.draw(true)
				this.ctx.restore()
			},
			touchStart(){return;},
			touchEnd(){return;},
			touchMove(){return;}
		}
	}
</script>

<style lang="scss" scoped>
	.bg {
		width: 100vw;
		height: 100vh;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 999;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.del {
		position: fixed;
		top: 144rpx;
		right: 75rpx;
		width: 57upx;
		height: 57upx;
		z-index: 1001;
	}

	.fixedBox {
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 19upx;
		z-index: 1001;
		width: 710upx;
		line-height: 114upx;
		background: #ECECEA;
		border-radius: 24upx;
		text-align: center;
		color: #1A1B1E;
	}

	.isCan {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		z-index: 1000;
		width: 557upx;
		height: 990upx;
		box-shadow: 0px 2upx 19upx 0upx rgba(0, 0, 0, 0.11);
		border-radius: 7upx;

	}
</style>
